package com.ruoyi.web.controller.community;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.community.domain.*;
import com.ruoyi.community.domain.integral.IntDetails;
import com.ruoyi.community.service.PayService;
import com.ruoyi.community.service.integral.IIntDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/community/pay")
public class PayController extends BaseController {

    @Autowired
    private PayService payService;

    @Autowired
    private IIntDetailsService intDetailsService;


    @RequestMapping("/test1")
    public String test(){
        logger.info("你好啊e");
        logger.warn("This is a warn message!");
        logger.error("This is error message!");
        return "server被调用了！:";
    }

//    @Autowired
//    private IntService intService;
    /**
     * app查询用户未缴费账单列表
     */

    @GetMapping("/list")
    public AjaxResult list(Integer houseId)
    {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        List<PayHisHouse> list = payService.selectPayHisHouseByHouseId(houseId);
        System.out.println(list);
        List<PayContent> payContentList= new ArrayList<PayContent>();
        for(int i=0;i<list.size();i++){
            PayContent p = new PayContent();
            PayHisHouse h= list.get(i);
            p.setDue(h.getDue());
            p.setPaid(h.getPaid());
            p.setIntegral(h.getIntegral());
            p.setOrderId(h.getOrderId());
            p.setPayFlag(h.getPayFlag());
            //System.out.println(h.getCostId());
            if(h.getCostId()>0) {
                PayCost payCost = payService.selectPayCost(h.getCostId());
                p.setName(payCost.getName());
                p.setUnitPrice(payCost.getUnitprice());
            }

            PayHistory payHistory = payService.selectPayHistoryByPrimaryKey(h.getHisId());
            p.setStartTime(sdf.format(payHistory.getStartTime()));
            p.setYear(payHistory.getStartTime().getYear()+1900);
            //System.out.println(payCost.getStartTime().getYear()+1900);


            payContentList.add(p);
        }
        //取得当年的年份
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        List<PayByYear> payByYear= new ArrayList<PayByYear>();
        for(int j=year; j>year-3; j--) {
            PayByYear p =new PayByYear();
            p.setYear(j);
            //System.out.println(p.getYear());
            int num =0;
            BigDecimal total = new BigDecimal("0.0");
            for (int i = 0; i < payContentList.size(); i++) {
                if (payContentList.get(i).getYear() == j) {
                    num++;
                    total = total.add(payContentList.get(i).getDue());
                }
            }
            p.setNum(num);
            p.setTotal(total);
            payByYear.add(p);
        }

        return AjaxResult.success(payByYear);
    }


    /**
     * app查询用户具体年份未缴费账单列表
     */

    @GetMapping("/listdetail")
    public AjaxResult listDetail(Integer houseId,Integer year)
    {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        List<PayHisHouse> list = payService.selectPayHisHouseByHouseId(houseId);
        System.out.println(list);
        List<PayContent> payContentList= new ArrayList<PayContent>();
        for(int i=0;i<list.size();i++){
            PayContent p = new PayContent();
            PayHisHouse h= list.get(i);
            p.setDue(h.getDue());
            p.setPaid(h.getPaid());
            p.setIntegral(h.getIntegral());
            p.setOrderId(h.getOrderId());
            p.setPayFlag(h.getPayFlag());
            p.setHisId(h.getHisId());
            //System.out.println(h.getCostId());
            if(h.getCostId()>0) {
                PayCost payCost = payService.selectPayCost(h.getCostId());
                p.setName(payCost.getName());
                p.setUnitPrice(payCost.getUnitprice());
            }
            if(h.getHisId()>0) {
                PayHistory payHistory = payService.selectPayHistoryByPrimaryKey(h.getHisId());
                p.setStartTime(sdf.format(payHistory.getStartTime()));
                p.setYear(payHistory.getStartTime().getYear() + 1900);
                //System.out.println(payCost.getStartTime().getYear()+1900);

            }
            int a= p.getYear();
            if(a==year){
                payContentList.add(p);
            }




        }

        return AjaxResult.success(payContentList);
    }

    /**
     * app查询用户历史缴费记录
     */

    @GetMapping("/record")
    public AjaxResult record(Integer houseId,Integer year)
    {
        List<PayOrders> list1 = payService.selectPayOrders(houseId);
        List<PayOrders> list = new ArrayList<PayOrders>();
        for(int i=0;i<list1.size();i++){
            PayOrders o= list1.get(i);
            int t = o.getTime().getYear()+1900;
            //System.out.println(t+"    "+year);
            if(t==year){
                // System.out.println(o.getId()+"///////////////////////");
                List<PayHisHouse> p = payService.selectPayHisHouse(o.getId());
                //System.out.println(p+"///////////////////////");
                for(int j= 0;j<p.size();j++) {
                    PayHisHouse p1 = p.get(j);
                    if (p1.getCostId() > 0) {
                        PayCost payCost = payService.selectPayCost(p1.getCostId());
                        p1.setName(payCost.getName());
                    }
                }

                o.setList(p);
                list.add(o);
            }

        }
        return AjaxResult.success(list);
    }

    /**
     app端点击支付1
     */
    @PostMapping("/payok1")
    public AjaxResult payok1(@RequestBody PayOKReceive payOKReceive){
        BigDecimal total = payOKReceive.getTotal();
        List<PayByYear> cart = payOKReceive.getCart();
        Integer houseId = payOKReceive.getHouseId();
        Integer integral = payOKReceive.getIntegral();
        BigDecimal paid = payOKReceive.getPaid();
        Long userId = payOKReceive.getUserId();
//        for(int i=0;i<cart.size();i++){
//            PayByYear p = cart.get(i);
//            System.out.println(p.getTotal());
//        }
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
        Date t = new Date();
        String str = sdf1.format(t);
        //新建一个payorder
        PayOrders payOrders =new PayOrders();
        payOrders.setDue(total);
        payOrders.setIntegral(integral);
        payOrders.setTime(t);
        payOrders.setHouseId(houseId);
        payOrders.setPaid(paid);
        payOrders.setPaymentMethod((byte) 1);
        long l = Long.valueOf(str).longValue()+integral;//生成一个订单号
        System.out.println(l);
        payOrders.setId(l);//设置ID为时间+integral
        payService.insertPayOrders(payOrders);


        //筛选出该houseid下的所有未支付账单，并且将其添加上year属性
        List<PayHisHouse> list = payService.selectPayHisHouseByHouseId(houseId);
        for(int i = 0;i<list.size();i++){
            PayHisHouse p = list.get(i);
            PayCost payCost = payService.selectPayCost(p.getCostId());
            p.setYear(payCost.getStartTime().getYear()+1900);
        }

        //修改账单状态
        for(int i=0;i<cart.size();i++){
            PayByYear p = cart.get(i);
            //按年份筛选出账单
            int year = p.getYear();
            for(int j=0;j<list.size();j++){
                PayHisHouse q= list.get(j);
                if(q.getYear() == year){
                    //修改支付状态
                    q.setPayFlag(true);
                    BigDecimal b = q.getDue();
                    BigDecimal s = total.subtract(BigDecimal.valueOf(integral));
                    BigDecimal a = b.divide(total,2).multiply(s);
                    BigDecimal w = b.divide(total,2).multiply(BigDecimal.valueOf(integral));
                    String str1 = w.toString();
                    System.out.println(str1);
                    Float f = Float.parseFloat(str1);
                    q.setPaid(a);
                    q.setIntegral(Math.round(f));
                    q.setOrderId(l);
                    payService.changePayHisHouse(q);

                }
            }


        }
        //修改积分
        if(integral>0) {
            IntDetails details = new IntDetails();
            details.setOperationId(1);
            details.setContent("缴费抵扣");
            details.setType(0);
            details.setIntegral(integral);
            intDetailsService.insertIntDetails(details);
        }

        return toAjax(1);

    }





    /**
     app端点击支付2
     */
    @PostMapping("/payok2")
    public AjaxResult payok2(@RequestBody PayOK1Receive payOKReceive){
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

        BigDecimal total = payOKReceive.getTotal();
        List<PayContent> cart = payOKReceive.getCart();
        Integer houseId = payOKReceive.getHouseId();
        // System.out.println(houseId+"      111111111111111111");
        Integer integral = payOKReceive.getIntegral();
        BigDecimal paid = payOKReceive.getPaid();
        Long userId = payOKReceive.getUserId();
//        for(int i=0;i<cart.size();i++){
//            PayByYear p = cart.get(i);
//            System.out.println(p.getTotal());
//        }
        SimpleDateFormat sdf2 =new SimpleDateFormat("yyyyMMddHHmmss");
        Date t = new Date();
        String str = sdf2.format(t);
        //新建一个payorder
        PayOrders payOrders =new PayOrders();
        payOrders.setDue(total);
        payOrders.setIntegral(integral);
        payOrders.setTime(t);
        payOrders.setHouseId(houseId);
        payOrders.setPaid(paid);
        payOrders.setPaymentMethod((byte) '1');
        long l = Long.valueOf(str).longValue()+integral;
        payOrders.setId(l);//设置ID为时间+integral
        payService.insertPayOrders(payOrders);


        //筛选出该houseid下的所有未支付账单
        for(int i=0;i<cart.size();i++) {
            PayContent p = cart.get(i);
//            PayHisHouseKey k =new PayHisHouseKey();
//            k.setHisId(p.getHisId());
//            k.setHouseId(houseId);
            List<PayHisHouse> payList = payService.selectByHisId(p.getHisId());
            if(payList!=null) {
                for(int d=0;d<payList.size();d++) {
                    PayHisHouse pay= payList.get(d);
                    Integer u = pay.getHouseId();
                    if(u.equals(houseId)) {
                        pay.setPayFlag(true);
                        BigDecimal b = pay.getDue();
                        BigDecimal s = total.subtract(BigDecimal.valueOf(integral));
                        BigDecimal a = b.divide(total, 2).multiply(s);
                        BigDecimal w = b.divide(total, 2).multiply(BigDecimal.valueOf(integral));
                        String str1 = w.toString();
                        System.out.println(str1);
                        Float f = Float.parseFloat(str1);
                        pay.setPaid(a);
                        pay.setIntegral(Math.round(f));
                        pay.setOrderId(l);
                        payService.changePayHisHouse(pay);
                    }
                }
            }
        }


        //修改积分

        if(integral>0) {
            IntDetails details = new IntDetails();
            details.setOperationId(1);
            details.setContent("缴费抵扣");
            details.setType(0);
            details.setIntegral(integral);
            intDetailsService.insertIntDetails(details);
        }

        return toAjax(1);



    }
}
